from flask import Flask, Blueprint
from app.extensions import db
import os
import sys
import importlib
import pkgutil

from app.models import load_models


def create_app(config_class='config.Config'):
    app = Flask(__name__)
    app.config.from_object(config_class)
    # 初始化扩展
    db.init_app(app)
    #加载模型
    load_models()
    # 自动创建表（仅当表不存在时）
    initTables(app)
    #  扫描蓝图 自动注册
    register_blueprints(app)
    return app


def register_blueprints(app):
    print("▁▂▃▄▅▆▇█==================== 注册蓝图开始 ====================█▇▆▅▄▃▂▁")
    # 获取 apps 目录下所有子目录
    apps_dir = os.path.dirname(__file__)
    # 获取api
    api_dir = os.path.join(apps_dir, 'api');
    for app_name in os.listdir(api_dir):
        # 忽略非目录文件和 __pycache__
        if not os.path.isdir(os.path.join(api_dir, app_name)) or app_name.startswith('__'):
            continue
        # 动态导入蓝图
        try:
            module = importlib.import_module(f'app.api.{app_name}.routes')
            blueprint = getattr(module, f'{app_name}_bp', None)
            if blueprint:
                app.register_blueprint(blueprint, url_prefix=f'/{app_name}')
                print(f"/{app_name}注入成功。")
        except ImportError as e:
            print(f"Failed to import {app_name}: {e}")
    print("█▇▆▅▄▃▂▁==================== 注册蓝图结束 ====================▁▂▃▄▅▆▇█")



def initTables(app: Flask):
    print("▁▂▃▄▅▆▇█==================== 初始化表结构开始 ====================█▇▆▅▄▃▂▁")
    with app.app_context():
        inspector = db.inspect(db.engine)
        existing_tables = inspector.get_table_names()
        # 仅创建不存在的表
        db_models = [cls for cls in db.Model.__subclasses__()]
        tables_to_create = [
            model.__table__ for model in db_models
            if model.__tablename__ not in existing_tables
        ]
        if tables_to_create:
            db.metadata.create_all(bind=db.engine, tables=tables_to_create)
            for table in tables_to_create:
                print(f"▋已创建新表: {table}")
        else:
            print("所有表已存在，无需创建")
    print("█▇▆▅▄▃▂▁==================== 初始化表结构结束 ====================▁▂▃▄▅▆▇█")